<template>
  <div class="login-container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
      <el-form-item label="用户名" prop="UserName">
        <el-input v-model="ruleForm.UserName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="Password">
        <el-input v-model="ruleForm.Password" show-password placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="验证码" prop="Captcha">
        <el-input v-model="ruleForm.Captcha" placeholder="请输入验证码" style="width: 200px;" />
        <canvas ref="canvasRef" @click="refreshCode" width="120" height="33" class="captcha-canvas"></canvas>
      </el-form-item>
      <el-form-item class="button-group">
        <el-button type="primary" @click="submitForm(ruleFormRef)" class="login-button">登录</el-button>
        <el-button @click="resetForm(ruleFormRef)" class="cancel-button">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'
import { read } from '@/axios/axiosHelper'
import { useCaptcha } from '@/composables/useCaptcha'

const store = useCounterStore()

interface RuleForm {
  UserName: string
  Password: string
  Captcha: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  UserName: '',
  Password: '',
  Captcha: ''
})

const rules = reactive<FormRules<RuleForm>>({
  UserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  Password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  Captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

const { canvasRef, currentCaptchaCode, refreshCode } = useCaptcha()

onMounted(() => {
  refreshCode()
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error submit!', fields)
      return
    }

    if (ruleForm.Captcha.toUpperCase() !== currentCaptchaCode.value.toUpperCase()) {
      ElMessage.error("验证码错误")
      refreshCode()
      return
    }

    try {
      const res = await axios.get("http://8.154.44.176:8000/r-read/api/User/Handle", {
        params: {
          UserName: ruleForm.UserName,
          Password: ruleForm.Password
        }
      })

      if (res.data.code === 600) {
        ElMessage.error("用户名不存在")
        return
      }

      if (res.data.code === 601) {
        ElMessage.error("密码错误")
        return
      }

      const { userName, userId, departmentId } = res.data.data
      const token = res.data.token

      // 更新store
      store.counterStore.userName = userName
      store.counterStore.userId = userId
      store.counterStore.departmentId = departmentId

      // 保存token和用户信息
      localStorage.Token = token
      sessionStorage.setItem("token", token)
      sessionStorage.setItem("UserId", userId)

      // 设置axios默认header
      axios.defaults.headers.common["Authorization"] = `Bearer ${token}`

      ElMessage.success("登录成功")
      location.href = '/GetMain'
    } catch (error) {
      ElMessage.error("登录失败，请稍后重试")
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  refreshCode()
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  min-width: 100%;
  background-color: #f4f4f9;
}

.demo-ruleForm {
  background-color: #fff;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  max-width: 600px;
}

.el-form-item {
  margin-bottom: 20px;
}

.captcha-canvas {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f9fafc;
  cursor: pointer;
  margin-left: 10px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.login-button {
  background-color: #409eff;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.login-button:hover {
  background-color: #3a8ee6;
}

.cancel-button {
  border-color: #dcdfe6;
  color: #606266;
  border-radius: 4px;
  transition: border-color 0.3s ease, color 0.3s ease;
}

.cancel-button:hover {
  border-color: #409eff;
  color: #409eff;
}
</style>